import { useSSRContext } from "vue"

interface SeoConfig {
    title: string
    description?: string
    keywords?: string
    image?: string
    url?: string
    type?: string
}


export function useSeo(config: SeoConfig | Ref<SeoConfig>) {
    const isServer = import.meta.env.SSR
    const ssrContext = isServer ? useSSRContext() : null

    const updateMeta = (conf: SeoConfig) => {
        const title = conf.title || 'website'
        const url = conf.url || (isServer ? ssrContext?.url : window.location.href)

        // SSR处理逻辑
        if (isServer) {
            if (!ssrContext!.head) ssrContext!.head = []

            // 让title换行并且空两个格
            ssrContext!.head.push(`  <title>${title}</title>`)
            // 添加带缩进的meta标签
            Object.entries({
                description: conf.description,
                keywords: conf.keywords,
                image: conf.image,
                url,
                type: conf.type || 'website'
            }).forEach(([key, value]) => {
                if (!value) return
                const tag = ['image', 'url', 'type'].includes(key)
                    ? `  <meta property="og:${key}" content="${value}">`
                    : `  <meta name="${key}" content="${value}">`
                ssrContext!.head.push(tag)
            })
            return
        }

        // CSR处理逻辑
        document.title = title

        const headEl = document.head;
        const titleEl = headEl.querySelector('title');
        const refNode = titleEl ? titleEl.nextSibling : headEl.firstChild;

        const metaData = {
            description: conf.description,
            keywords: conf.keywords,
            image: conf.image,
            url,
            type: conf.type || 'website'
        }

        Object.entries(metaData).forEach(([key, value]) => {
            if (!value) return;

            // 创建 <meta> 节点
            const tag = document.createElement('meta');
            if (['image', 'url', 'type'].includes(key)) {
                tag.setAttribute('property', `og:${key}`);
            } else {
                tag.setAttribute('name', key);
            }
            tag.setAttribute('content', value);

            // 插入到 <title> 之后
            headEl.insertBefore(tag, refNode);
        });
    }

    // SSR立即执行，CSR使用watchEffect
    if (isServer) {
        updateMeta(unref(config))
    } else {
        watchEffect(() => updateMeta(unref(config)))
    }
}